package com.gxp.controller.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gxp.pojo.Authority;
import com.gxp.pojo.Role;
import com.gxp.pojo.User;
import com.gxp.service.AuthorityService;
import com.gxp.service.RoleService;
import com.gxp.service.UserService;
import com.gxp.util.common.GXPConstant;
import com.gxp.util.common.GXPUtil;
import com.gxp.util.security.Des;

@Controller
public class UserController {
	
	Logger logger = Logger.getLogger(UserController.class);
	
	@Autowired
	private UserService userSerivce;
	
	@Autowired
	private AuthorityService authSerivce;

	@Autowired
	private RoleService roleSerivce;

	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_VIEW')")
	@RequestMapping(value = "/admin/user/external/list", method = RequestMethod.GET)
	public ModelAndView list() {

		logger.debug("UserController list is invoked.........");
		List<User> users = userSerivce.getAllBuyers();
		logger.debug("users size: " +  users.size());
		logger.debug("user id: " +  ((User)users.get(0)).getUserId());
		logger.debug("user id: " +  ((User)users.get(0)).getUserM());
		logger.debug("user id: " +  ((User)users.get(0)).getRegDateStr());
		ModelAndView mav = new ModelAndView();
		mav.addObject("users", users);
		mav.setViewName("admin/user/extUserList");
		return mav;
	}
	
	@RequestMapping(value="/admin/user/external/view/{userId}/",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_VIEW')")
	@ResponseBody
	public User viewExternalUserInfo(@PathVariable String userId) {
		logger.debug("userId viewExternalUserInfo is invoked.........");
		logger.debug("userId: " + userId);
		User findUser = new User();
		findUser.setUserId(userId);
		return userSerivce.getUserInfo(findUser);
	}
	
	@RequestMapping(value="/admin/user/external/status/update/{userId}/{status}",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_UPDATE')")
	@ResponseBody
	public String updateExtUserStatus(@PathVariable String userId, @PathVariable int status) {
		logger.debug("UserController updateExtUserStatus is invoked.........");
		userSerivce.updateUserStatus(userId, status);
		return GXPUtil.getJsonString("success", false, String.valueOf(status));
	}

	@RequestMapping(value="/admin/user/internal/view/{userId}/",method=RequestMethod.POST)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_VIEW')")
	@ResponseBody
	public User viewUserInfo(@PathVariable String userId) {
		logger.debug("userId iewUserInfo is invoked.........");
		logger.debug("userId: " + userId);
		User findUser = new User();
		findUser.setUserId(userId);
		return userSerivce.getUserInfo(findUser);
	}
	
	@RequestMapping(value = "/admin/user/internal/list", method = RequestMethod.GET)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_VIEW')")
	public ModelAndView listAdminUsers() {
		logger.debug("UserController listAdminUsers is invoked.........");
		List<User> users = userSerivce.getAllAdminUsers();		
		ModelAndView mav = new ModelAndView();
		mav.addObject("users", users);
		mav.setViewName("admin/user/intUserList");
		return mav;
	}
	
	@RequestMapping(value="/admin/user/internal/delete/{userId}/",method=RequestMethod.POST)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_DELETE')")
	@ResponseBody
	public String delAdminUser(@PathVariable String userId) {
		logger.debug("UserController delAdinUser is invoked.........");
		userSerivce.deleteUserById(userId);
		return GXPUtil.getJsonString("success", false, "");
	}
	
	@RequestMapping(value="/admin/user/internal/save",method=RequestMethod.POST)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_ADD')")
	@ResponseBody
	public String saveAdminUser(User user) {
		logger.debug("UserController saveAdminUser is invoked.........");
		userSerivce.addAdminUser(user);
		return GXPUtil.getJsonString("success", false, "");
	}
	@RequestMapping(value="/admin/user/internal/add",method=RequestMethod.GET)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_ADD')")
	public ModelAndView addAdminUser() {
		logger.debug("UserController addAdminUser is invoked.........");
		
		List<Role> roleList =  roleSerivce.findAllIntRole();
		ModelAndView mav = new ModelAndView();
		mav.addObject("roleList", roleList);
		mav.setViewName("admin/user/intUserAdd");
		return mav;
	}	
	
	@RequestMapping(value="/user/checkuserid",method=RequestMethod.POST)
	@ResponseBody
	public boolean checkUserId(String userId) {
		logger.debug("UserController checkUserId is invoked.........");
		String userName = userSerivce.checkUserId(userId);
		return userName == null ? true : false;
	}
	
	
	@RequestMapping(value="/admin/user/internal/edit/{userId}/",method=RequestMethod.GET)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_UPDATE')")
	public ModelAndView editAdminUser(@PathVariable String userId) {
		logger.debug("UserController editAdminUser is invoked.........");
		List<String> errors = new ArrayList<String>();
		ModelAndView mav = new ModelAndView();
		if (GXPUtil.isEmpty(userId)) {
			errors.add("msg.error.user.notfound");
			mav.addObject(GXPConstant.KEY_ERRORS, errors);
			mav.setViewName("admin/user/intUserList");
			return mav;
		}
		User findUser = new User();
		findUser.setUserId(userId);
		User user = userSerivce.findById(findUser);
		if (GXPUtil.isEmpty(user)) {
			errors.add("msg.error.user.notfound");
			mav.addObject(GXPConstant.KEY_ERRORS, errors);
			mav.setViewName("admin/user/intUserList");
			return mav;
		}
		List<Role> roleList =  roleSerivce.findAllIntRole();
		mav.addObject("user", user);
		mav.addObject("roleList", roleList);
		mav.setViewName("admin/user/intUserEdit");
		return mav;
	}
	
	@RequestMapping(value="/admin/user/checkpassword",method=RequestMethod.POST)
	@ResponseBody
	public boolean checkPassword(User user) {
		logger.debug("UserController checkPassword is invoked.........");
		logger.debug("user id : " + user.getUserId());
		logger.debug("password: " + user.getPassword());
		return userSerivce.checkPassword(user);
	}
	
	@RequestMapping(value="/admin/user/internal/update",method=RequestMethod.POST)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_UPDATE')")
	@ResponseBody
	public String updateUserInfo(User user) {
		logger.debug("UserController updateUserInfo is invoked.........");
		userSerivce.updateUserInfo(user);
		roleSerivce.updateUserRole(user.getUserId(), user.getSelectedRoleList());
		return GXPUtil.getJsonString("success", false, "");
	}
	
	@RequestMapping(value="/admin/user/internal/pws/update",method=RequestMethod.POST)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_UPDATE')")
	@ResponseBody
	public String updateUserPwd(User user) {
		logger.debug("UserController updateUserPwd is invoked.........");
		String userId = user.getUserId();
		String password = user.getPassword();
		String encryptPassword = Des.encryptUserPassord(userId, password);
		user.setPassword(encryptPassword);
		userSerivce.updateUserPassword(user);
		return GXPUtil.getJsonString("success", false, "");
	}
	
	@RequestMapping(value = "/admin/internal/auth", method = RequestMethod.GET)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_VIEW')")
	/*@PreAuthorize("hasRole('ROLE_ADMIN_ALL') or hasRole('ROLE_ADMIN_USER')")*/
	public ModelAndView intAuthlist() {

		logger.debug("UserController intAuthlist is invoked.........");
		List<Authority> authList =  authSerivce.findAllAuth();
		ModelAndView mav = new ModelAndView();
		mav.addObject("authList", authList);
		mav.setViewName("admin/user/intAuthList");
		return mav;
	}
	
	@RequestMapping(value = "/admin/internal/role", method = RequestMethod.GET)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_VIEW')")
	/*@PreAuthorize("hasRole('ROLE_ADMIN_ALL') or hasRole('ROLE_ADMIN_USER')")*/
	public ModelAndView intRoleList() {

		logger.debug("UserController intRoleList is invoked.........");
		List<Role> roleList =  roleSerivce.findAllIntRole();
		for (Role role : roleList) {
			List<Authority> authList = role.getPermissionList();
			logger.debug("permission size: " + authList.size());
			StringBuffer authIdStr = new StringBuffer("");
			for (int i = 0; i < authList.size(); i++) {
				Authority auth = authList.get(i);
				authIdStr.append(auth.getAuthId()).append(',');
			}
			role.setAuthIdStr(authIdStr.toString());
		}
		List<Authority> authList =  authSerivce.findAllAuth();
		ModelAndView mav = new ModelAndView();
		mav.addObject("roleList", roleList);
		mav.addObject("authList", authList);
		mav.setViewName("admin/user/intRoleList");
		return mav;
	}
	
	@RequestMapping(value = "/admin/role/auth/update", method = RequestMethod.POST)
	@PreAuthorize("hasAnyRole('ROLE_ADMIN_ALL','ROLE_ADMIN_USER') and hasRole('PERM_USER_UPDATE')")
	@ResponseBody
	public Role updateRoleAuthRelation(Role role) {

		logger.debug("UserController updateRoleAuthRelation is invoked.........");
		logger.debug(role.getRoleId());
		roleSerivce.updateRoleAuthRelation(role.getRoleId(), role.getSelectedAuthArr());
		return roleSerivce.findById(role.getRoleId());
	}
	
}
